package com.xyxy.platform.openapi.member.v1.web.controller;

import com.xyxy.platform.modules.core.beanvalidator.BeanValidators;
import com.xyxy.platform.modules.core.beanvalidator.group.A;
import com.xyxy.platform.modules.core.beanvalidator.group.B;
import com.xyxy.platform.modules.core.utils.IpUtils;
import com.xyxy.platform.modules.core.utils.PasswordEncode;
import com.xyxy.platform.modules.core.utils.ResponseUtils;
import com.xyxy.platform.modules.core.web.controller.BaseController;
import com.xyxy.platform.modules.core.web.response.ResponseMessage;
import com.xyxy.platform.modules.entity.member.Member;
import com.xyxy.platform.modules.entity.member.MemberLoginLog;
import com.xyxy.platform.modules.service.common.sms.SmsService;
import com.xyxy.platform.modules.service.member.MemberLoginLogService;
import com.xyxy.platform.modules.service.member.MemberService;
import com.xyxy.platform.modules.service.member.vo.SimpleMember;
import com.xyxy.platform.openapi.AppConstants;
import com.xyxy.platform.openapi.common.security.RequiresPermissions;
import com.xyxy.platform.openapi.common.web.bind.annotation.CurrentLoginMember;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Validator;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;

/**
 * 登录, 注册, 密码找回之类..
 * Created by VirtueCai on 15/12/18.
 */
@RestController
@RequestMapping("/member/v1")
public class AuthorizationController extends BaseController {

    @Autowired
    private Validator validator;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberLoginLogService loginLogService;
    
    @Autowired
    private SmsService smsService;


    /**
     * 注册
     *
     * @param memberForm ActionForm
     * @return
     */
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ResponseMessage<?> register(MemberForm memberForm) {
        BeanValidators.validateWithException(validator, memberForm, A.class);
        if (!memberService.exist(memberForm.getMobile())) {
        	
        	String code = request.getParameter("code");//手机验证码
        	if(StringUtils.isEmpty(code)){
        		return ResponseUtils.jsonFail(false, "注册失败, 验证码为空!");
        	}
        	if( !smsService.verifyCode(memberForm.getMobile(), Long.parseLong(code)) ){
        		return ResponseUtils.jsonFail(false, "注册失败, 验证码不正确!");
        	}
        	
            Member member = new Member();
            member.setMobile(memberForm.getMobile());
            //member.setPassword(PasswordEncode.getENCPassword(memberForm.getPassword()));
            member.setPassword(memberForm.getPassword());
            member.setUserName(memberForm.getMobile());
            memberService.register(member);
            return ResponseUtils.jsonSuccess(true, "注册成功!");
        } else {
            return ResponseUtils.jsonFail(false, "注册失败, 该手机号已注册!");
        }
    }

    /**
     * 登录
     *
     * @param memberForm ActionForm
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ResponseMessage<?> login(MemberForm memberForm) {

        // 调用JSR303 Bean Validator进行校验, 异常将由RestExceptionHandler统一处理.
        BeanValidators.validateWithException(validator, memberForm, A.class);

        ResponseMessage<?> result;

        // 记录登录日志
        MemberLoginLog loginLog = new MemberLoginLog();
        loginLog.setLoginIp(IpUtils.getIpAddr(request));
        loginLog.setLoginTime(new Date());

        Member member;
        try {
            //member = memberService.login(memberForm.getMobile(),PasswordEncode.getENCPassword(memberForm.getPassword()));
            member = memberService.login(memberForm.getMobile(),memberForm.getPassword());
        } catch (Exception e) {
            return ResponseUtils.jsonFail(null, e.getMessage());
        }
        Map<String, String> memberMap = null;
        try {
        	member.setPassword("");
            memberMap = BeanUtils.describe(member);
            memberMap.remove("class");
        } catch (Exception e) {
            logger.error("member bean to map failure! e: {}", e.getMessage());
        }
        if (null != member) {

            loginLog.setIsSuccess(1);
            loginLog.setMemberId(member.getId());

            String token = memberService.generateToken(member);
            memberMap.put(AppConstants.REQUEST_TOKEN_KEY, token);
            result = ResponseUtils.jsonSuccess(memberMap, "登录成功!");
        } else {
            loginLog.setIsSuccess(0);
            result = ResponseUtils.jsonSuccess(null, "用户名或密码有误, 登录失败!");
        }
        //异步
        loginLogService.createLoginLog(loginLog);
        return result;
    }

    /**
     * 退出登录
     *
     * @param simpleMember 取其中 token
     * @return
     */
    @RequiresPermissions
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    public ResponseMessage<?> logout(@CurrentLoginMember SimpleMember simpleMember) {
        memberService.deleteToken(simpleMember.getToken());
        return ResponseUtils.jsonSuccess(null, "退出登录成功!");
    }

    /**
     * 重置密码
     *
     * @return
     */
    @RequestMapping(value = "reset_password", method = RequestMethod.POST)
    public ResponseMessage<?> resetPassword(MemberForm memberForm) {
        BeanValidators.validateWithException(validator, memberForm, B.class);
        boolean result = memberService.resetPassword(memberForm.getId(), memberForm.getNewPassword());
        if (result) {
            return ResponseUtils.jsonSuccess(null, "重置密码成功!");
        } else {
            return ResponseUtils.jsonFail(null, "重置密码失败!");
        }
    }

}

/**
 * 请求数据绑定, 用于多个mapping(Action)
 * 分别是 A,B 组参数
 */
class MemberForm implements Serializable {

    //用户ID
    @NotNull(groups = {B.class})
    private Long id;

    //手机号码
    @NotNull(groups = {A.class, B.class})
    @Pattern(regexp = "^1\\d{10}$", groups = {A.class, B.class}, message = "{validator.mobile.number}")
    private String mobile;

    //密码
    @NotNull(groups = {A.class})
    @Length(min = 6, max = 60, groups = {A.class})
    private String password;

    //新密码
    @NotNull(groups = {B.class})
    @Length(min = 6, max = 60, groups = {B.class})
    private String newPassword;


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

}
